package com.eve.util.bank;

/**
 *
 * Luhn算法,校验银行卡是否符合规范
 *
 * @author: ivan.yao<haif.yao@gmail.com>
 * @date: 16/7/6.
 */
public class Luhn {


    public static void main(String[] args) {
        System.out.println(Luhn.validate("6222530174787015"));
        System.out.println(Luhn.validate("6222081202009727957"));
        System.out.println(Luhn.validate("6222024000068898135"));
        System.out.println(Luhn.validate("6212264000044465017"));
    }

    /**
     * Validate a number string using Luhn algorithm
     *
     * @param number
     * @return
     */
    public static boolean validate(String number) {
        int s1 = 0, s2 = 0;
        String reverse = new StringBuffer(number).reverse().toString();
        for (int i = 0 ;i < reverse.length();i++) {
            int digit = Character.digit(reverse.charAt(i), 10);
            if(i % 2 == 0) { s1 += digit; }
            else {
                s2 += 2 * digit;
                if (digit >= 5) { s2 -= 9; }
            }
        }
        return (s1 + s2) % 10 == 0;
    }

}
